//
// const commentButton = document.querySelector('.comment-section1');
// const commentBox = document.querySelector('.comment-section');
//
// commentButton.addEventListener('click', function () {
//     commentBox.classList.add('show');
// });
// let closeButton=document.getElementsByClassName('close')[0]
// closeButton.addEventListener('click', function () {
//     commentBox.classList.remove('show');
// });
let reply_sections=document.getElementsByClassName('reply-section')
for(let i=0;i<reply_sections.length;i++){
    reply_sections[i].addEventListener('click',()=>{
        let sub_comments=document.getElementsByClassName('sub-comments')[i]
        sub_comments.style.display='block'
        reply_sections[i].textContent='——展开更多回复∨'
    })
}
let closeButton=document.getElementsByClassName('close')[0]
closeButton.addEventListener('click', function () {
    commentBox.classList.remove('show');
});
// const comment_section = document.querySelector('.comment-section');

// comment_section.addEventListener('wheel', function (event) {
//     // 阻止滚动事件冒泡到外层容器
//     event.stopPropagation();
// });
const commentButton = document.querySelector('.comment-section1');
const commentBox = document.querySelector('.comment-section');

commentButton.addEventListener('click', function () {
    commentBox.classList.add('show');
});
// const share_outer=document.getElementsByClassName('share-outer')[0]
// const share_section=document.getElementsByClassName('share-section')[0]
// share_section.addEventListener('click',()=>{
//     share_outer.style.height='50px'
// })
// let follow_button = document.querySelector('.follow-button');
// follow_button.addEventListener('click', function() {
//     let userId = this.value;
//     console.log(userId);
//     // const userIdNum = Number(value);
//     if (this.classList.contains('following')) {
//         // 当前是已关注状态，执行取消关注逻辑
//         $.ajax({
//             url: `/cancelFollow?id=${userId}`,
//             type: 'POST',
//             success: function(result) {
//                 showCustomAlert('取消关注成功', 3000);
//                 follow_button.classList.remove('following');
//                 follow_button.textContent = '关注';
//             },
//             error: function(error) {
//                 showCustomAlert('取消关注失败: ' + error.statusText, 3000);
//             }
//         });
//     }
//     else {
//         // 当前是未关注状态，执行关注逻辑
//         $.ajax({
//             url: `/followOthers?id=${userId}`,
//             type: 'GET',
//             success: function(result) {
//                 showCustomAlert('关注成功', 3000);
//                 follow_button.classList.add('following');
//                 follow_button.textContent = '取消关注';
//             },
//             error: function(error) {
//                 showCustomAlert('关注失败: ' + error.statusText, 3000);
//             }
//         });
//     }
// })
//
// let like_icon_container=document.getElementsByClassName('like-icon-container')[0]
// console.log(like_icon_container)
// like_icon_container.addEventListener('click', function () {
//
//     let like_icon = document.getElementsByClassName('like-icon')[0]
//     let like_value = document.getElementsByClassName('like-section')[0].dataset.value
//     const postIdNum = Number(like_value);
//     console.log(like_icon.style.color)
//     // console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
//     if (window.getComputedStyle(like_icon).color === 'rgb(140, 145, 149)') {
//
//         $.ajax({
//             url: `/videos/like?postId=${like_value}`,
//
//             type: 'POST',
//             data: {videoId: postIdNum},
//             success: function (result) {
//                 showCustomAlert(result.message, 3000)
//
//                 like_icon.style.color = 'rgba(255,0,0,1)'
//                 // likes[i].style.color= 'rgba(255,0,0)'
//                 console.log('发送点赞请求到:', this.url);
//                 console.log(result)
//
//                 let like_count=document.getElementsByClassName('like-count')[0]
//                 like_count.textContent=`${result.likeCount}`
//             },
//             error: function (error) {
//                 showCustomAlert('点赞失败: ' + error.status + ' ' + error.statusText, 3000);
//                 console.log(error);
//                 console.log('发送点赞请求到:', this.url);
//             }
//
//         })
//
//     } else {
//         console.log(1111111)
//         $.ajax({
//             url: `/videos/cancelLike?postId=${like_value}`,
//
//             type: 'POST',
//             data: {videoId: postIdNum},
//             success: function (result) {
//                 showCustomAlert(result.message, 3000)
//                 like_icon.style.color = 'rgb(140, 145, 149)'
//                 let like_count=document.getElementsByClassName('like-count')[0]
//                 like_count.textContent=`${result.likeCount}`
//                 console.log(result)
//                 console.log('发送点赞请求到:', this.url);
//             },
//             error: function (error) {
//                 showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
//                 console.log(error);
//                 console.log('发送点赞请求到:', this.url);
//             }
//
//         })
//     }
//
// })
//
// function showCustomAlert(message, duration) {
//     let customAlert = document.getElementById('customAlert');
//     if (!customAlert) {
//         div_outter=document.createElement('div');
//         customAlert = document.createElement('div');
//         customAlert.id = 'customAlert';
//         // customAlert.style.margin='7px 12px';
//         const alertMessage = document.createElement('p');
//         alertMessage.id = 'alertMessage';
//         customAlert.appendChild(alertMessage);
//
//         document.body.appendChild(customAlert);
//     }
//
//     const alertMessage = document.getElementById('alertMessage');
//
//     alertMessage.textContent = message;
//     if(alertMessage.textContent==null){
//         customAlert.style.display = 'none';
//     }
//
//     customAlert.style.display = 'block';
//     setTimeout(() => {
//         customAlert.style.display = 'none';
//     }, duration);
// }
let currentPage = 1; // 当前页码
let totalPages = 1; // 总页数
let isLoading = false; // 加载状态标记
let totalCommentsCount = 0; // 累计评论数
let hasMoreData = true;
let currentPostId = null;
function articleDetail(postId) {
    const postIdNum = Number(postId);
    console.log(postIdNum)
    const comment_item_outer = document.querySelector('.comment-item-outer');
    comment_item_outer.innerHTML = '';
    currentPage=1;
    totalCommentsCount=0;
    setupInfiniteScroll(); // 首次加载完成后启动滚动监听
    // 初始化加载第一页
    loadComments(postIdNum,currentPage);
    //滚动监听
    function setupInfiniteScroll() {
        console.log('setupInfiniteScroll 被调用');
        const commentContainer = document.querySelector('.comment-section');
        if (!commentContainer) return;

        commentContainer.addEventListener('scroll', () => {
            const scrollTop = commentContainer.scrollTop;
            const containerHeight = commentContainer.clientHeight;
            const contentHeight = commentContainer.scrollHeight;

            if (scrollTop + containerHeight >= contentHeight - 300 &&
                currentPage < totalPages && !isLoading) {
                currentPage++;
                loadComments(postIdNum,currentPage);
            }
        });
    }

    // 加载评论函数
    function loadComments(postIdNum,page) {
        console.log(postIdNum)
        isLoading = true;
        console.log(250)
        $.ajax({
            url: `/videosComments?videoId=${postIdNum}&pageNum=${page}`,
            type: 'GET',
            success: function(result) {
                const id = result.userId;
                const comments = result.comments;
                const commentUsers = result.commentUsers;
                totalPages = result.totalPages; // 更新总页数
                // **更新累计评论数**
                console.log(result)
                totalCommentsCount += comments.length;


                console.log(comments)
                console.log(id)
                // 首次加载时初始化列表
                const totalComments=document.getElementsByClassName('total-comments')[0]
                const comment_count=document.getElementsByClassName('comment-count')[0]
                totalComments.innerHTML=`全部评论 <span> ${result.commentsCount}</span>`
                comment_count.innerHTML=`${result.commentsCount}`
                let commentListHTML = comments.length === 0 ?

                    '<div class="empty-comment" xmlns="http://www.w3.org/1999/html"><i class="iconfont cat">&#xe61c;</i><br><span >暂无评论</span></div>' :
                    comments.map((comment, i) => `
                            <div class="comment-item" style="padding-top: 10px;">
                                <div class="comment-user">
                                    <img src="${commentUsers[i].avatar}" alt="用户头像" class="avatar">
                                    <span class="username">${commentUsers[i].username}</span>
                                </div>
                                <div class="comment-content" data-value="${commentUsers[i].userId}">
                                    <p>${comment.content}</p>
                                    <span class="comment-time">${comment.createdAt}</span>
                                </div>
                                <div class="comment-actions">
                                    <span class="reply-icon" data-value="${comment.id}"><i class="iconfont comment-delete comment_like_icon">&#xe653;</i>点赞</span>
                                    <span class="share-icon2" data-value="${comment.id}"><i class="iconfont comment-delete">&#xe63f;</i>删除</span>
                                </div>
                            </div>
                        `).join('');

                const commentItemOuter = document.getElementsByClassName('comment-item-outer')[0];
                if (page === 1) {
                    commentItemOuter.innerHTML = commentListHTML; // 替换内容
                } else {
                    commentItemOuter.innerHTML += commentListHTML; // 仅分页加载时追加（可选）
                }
                console.log(commentListHTML)


                const pageSize = 5; // 根据后端接口设置
                const startIndex = (page - 1) * pageSize;
                const endIndex = page * pageSize - 1;

                const allShareIcons = document.getElementsByClassName('share-icon2');
// 提取当前页的删除按钮（基于页码和每页条数）
                const currentPageShareIcons = Array.from(allShareIcons).slice(startIndex, endIndex + 1);
                const replyIcons = document.getElementsByClassName('reply-icon');
                const commentLikeIcons = document.getElementsByClassName('comment_like_icon');
                console.log(commentUsers)

                for (let i = 0; i < comments.length; i++) {
                    const commentUser = commentUsers[i];

                    console.log(id)
                    console.log(commentUser.id)
                    if (String(id) === String(commentUser.id)) {
                        const shareIcon = currentPageShareIcons[i]; // 当前页内的相对索引
                        shareIcon.style.display = 'block';
                        console.log(1111)
                    }
                }

                // 绑定删除事件
                Array.from(currentPageShareIcons).forEach(shareIcon => {
                    shareIcon.addEventListener('click', () => {
                        const commentId = Number(shareIcon.dataset.value);
                        console.log(commentId)
                        $.ajax({
                            url: `/videos/comment/user`,
                            type: 'POST',
                            data: { commentId:commentId },
                            success: (result) => {
                                showCustomAlert('删除成功', 3000);
                                // 删除后重新加载当前页（可选：优化为局部删除）
                                console.log('已经删除')
                                console.log(commentId)
                                totalCommentsCount = 0;
                                if (comments.length === 0 && currentPage > 1) {
                                    currentPage--;

                                }
                                loadComments(postIdNum, currentPage); // 重新加载上一页

                            },
                            error: (error) => {
                                showCustomAlert('删除失败: ' + error.statusText, 3000);
                            }
                        });
                    });
                });

                // 绑定点赞事件
                Array.from(replyIcons).forEach((replyIcon, i) => {
                    replyIcon.addEventListener('click', () => {
                        const commentId = Number(replyIcon.dataset.value);
                        if (replyIcon.style.color === 'red') {
                            // 取消点赞
                            $.ajax({
                                url: `/videos/cancelLike`,
                                type: 'POST',
                                data: { commentsId: commentId },
                                success: () => {
                                    showCustomAlert('取消点赞成功', 3000);
                                    commentLikeIcons[i].style.color = 'rgb(82, 91, 100)';
                                    replyIcon.style.color = 'rgb(82, 91, 100)';
                                }
                            });
                        } else {
                            // 点赞
                            $.ajax({
                                url: `/videos/like`,
                                type: 'POST',
                                data: { commentsId: commentId },
                                success: () => {
                                    showCustomAlert('点赞成功', 3000);
                                    commentLikeIcons[i].style.color = 'red';
                                    replyIcon.style.color = 'red';
                                }
                            });
                        }
                    });
                });

                // 初始化点赞状态
                comments.forEach((comment, i) => {
                    if (comment.isLiked) {
                        commentLikeIcons[i].style.color = 'red';
                        replyIcons[i].style.color = 'red';
                    }
                });

                isLoading = false; // 加载完成
            },
            error: (error) => {
                currentPage--; // 加载失败时回退页码
                isLoading = false;
                showCustomAlert('加载评论失败: ' + error.statusText, 3000);
            }
        });
    }
}

function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}

let like_icon_container=document.getElementsByClassName('like-icon-container')[0]
console.log(like_icon_container)
like_icon_container.addEventListener('click', function () {

    let like_icon = document.getElementsByClassName('like-icon')[0]
    let like_value = document.getElementsByClassName('like-section')[0].dataset.value
    const postIdNum = Number(like_value);
    console.log(like_icon.style.color)
    // console.log(window.getComputedStyle(top_story_content_footer_button_likes[i]).color)
    if (window.getComputedStyle(like_icon).color === 'rgb(82, 91, 100)') {

        $.ajax({
            url: `/videos/like?postId=${like_value}`,

            type: 'POST',
            data: {postId: postIdNum},
            success: function (result) {
                showCustomAlert(result.message, 3000)

                like_icon.style.color = 'rgba(255,0,0,1)'
                // likes[i].style.color= 'rgba(255,0,0)'
                console.log('发送点赞请求到:', this.url);
                console.log(result)

                let like_count=document.getElementsByClassName('like-count')[0]
                like_count.textContent=`${result.likeCount}`
            },
            error: function (error) {
                showCustomAlert(result.message + error.status + ' ' + error.statusText, 3000);
                console.log(error);
                console.log('发送点赞请求到:', this.url);
            }

        })

    } else {
        console.log(1111111)
        $.ajax({
            url: `/videos/cancelLike?postId=${like_value}`,

            type: 'POST',
            data: {postId: postIdNum},
            success: function (result) {
                showCustomAlert('取消点赞', 3000)
                like_icon.style.color = 'rgba(82,91,100,1)'
                let like_count=document.getElementsByClassName('like-count')[0]
                like_count.textContent=`${result.likeCount}`
                console.log(result)
                console.log('发送点赞请求到:', this.url);
            },
            error: function (error) {
                showCustomAlert('取消点赞失败: ' + error.status + ' ' + error.statusText, 3000);
                console.log(error);
                console.log('发送点赞请求到:', this.url);
            }

        })
    }

})

// document.addEventListener('DOMContentLoaded', () => {
//     const backBtn = document.getElementById('backBtn');
//
//
//     backBtn.addEventListener('click', (e) => {
//         e.preventDefault();
//
//         // 等待动画完成后返回上一页
//         setTimeout(() => {
//             history.back();
//         }, 500); // 动画持续时间
//     });
// });
let comment_count=document.getElementsByClassName('comment-count')[0]



function publish(postId) {
    currentPostId = Number(postId);

    let content = document.getElementsByClassName('comment-input-detail')[0].value;
    console.log(content);
    let comment_input_detail = document.getElementsByClassName('comment-input-detail')[0];

    $.ajax({
        url: `/videos/comment？videoId=${currentPostId}&content=${content}`,
        type: 'POST',
        success: function(result) {
            showCustomAlert('评论成功', 3000);
            console.log(result);
            comment_input_detail.value = '';

            // 重置分页状态，重新加载评论
            currentPage = 1;
            hasMoreData = true;

            // 清空现有评论，加载第一页
            const comment_item_outer = document.querySelector('.comment-item-outer');
            comment_item_outer.innerHTML = '';
            loadComments(currentPostId, currentPage);

        },
        error: function(error) {
            showCustomAlert('评论失败: ' + error.status + ' ' + error.statusText, 3000);
            console.log(error);
        }
    });
    setupInfiniteScroll(); // 首次加载完成后启动滚动监听
}
function setupInfiniteScroll() {
    const commentContainer = document.querySelector('.comment-section');
    if (!commentContainer) return;

    commentContainer.addEventListener('scroll', () => {
        const scrollTop = commentContainer.scrollTop;
        const containerHeight = commentContainer.clientHeight;
        const contentHeight = commentContainer.scrollHeight;

        if (scrollTop + containerHeight >= contentHeight - 300 &&
            currentPage < totalPages && !isLoading) {
            currentPage++;
            loadComments(currentPostId,currentPage);
        }
    });
}
// 加载评论函数

function loadComments(postIdNum,page) {
    isLoading = true;
    $.ajax({
        url: `/videosComments?videoId=${postIdNum}&pageNum=${page}&pageSize=5`,
        type: 'GET',
        success: function(result) {
            const id = result.userId;
            const comments = result.comments;
            const commentUsers = result.commentUsers;
            totalPages = result.totalPages; // 更新总页数
            // **更新累计评论数**
            // totalCommentsCount += comments.length;
            console.log(result)
            console.log(id)
            // 首次加载时初始化列表
            const totalComments=document.getElementsByClassName('total-comments')[0]
            const comment_count=document.getElementsByClassName('comment-count')[0]
            totalComments.innerHTML=`全部评论 <span> ${result.commentsCount}</span>`
            comment_count.innerHTML=`${result.commentsCount}`
            let commentListHTML = comments.length === 0 ?
                '<div class="empty-comment" xmlns="http://www.w3.org/1999/html"><i class="iconfont cat">&#xe61c;</i><br><span >暂无评论</span></div>' :
                comments.map((comment, i) => `
                            <div class="comment-item" style="padding-top: 10px;">
                                <div class="comment-user">
                                    <img src="${commentUsers[i].avatar}" alt="用户头像" class="avatar">
                                    <span class="username">${commentUsers[i].username}</span>
                                </div>
                                <div class="comment-content" data-value="${commentUsers[i].userId}">
                                    <p>${comment.content}</p>
                                    <span class="comment-time">${comment.createdAt}</span>
                                </div>
                                <div class="comment-actions">
                                    <span class="reply-icon" data-value="${comment.id}"><i class="iconfont comment-delete comment_like_icon">&#xe653;</i>点赞</span>
                                    <span class="share-icon2" data-value="${comment.id}"><i class="iconfont comment-delete">&#xe63f;</i>删除</span>
                                </div>
                            </div>
                        `).join('');
            const commentItemOuter = document.getElementsByClassName('comment-item-outer')[0];
            if (page === 1) {

                commentItemOuter.innerHTML = commentListHTML; // 替换内容
            } else {
                commentItemOuter.innerHTML += commentListHTML; // 仅分页加载时追加（可选）
            }



            const pageSize = 5; // 根据后端接口设置
            const startIndex = (page - 1) * pageSize;
            const endIndex = page * pageSize - 1;

            const allShareIcons = document.getElementsByClassName('share-icon2');
// 提取当前页的删除按钮（基于页码和每页条数）
            const currentPageShareIcons = Array.from(allShareIcons).slice(startIndex, endIndex + 1);
            const replyIcons = document.getElementsByClassName('reply-icon');
            const commentLikeIcons = document.getElementsByClassName('comment_like_icon');
            console.log(commentUsers)

            for (let i = 0; i < comments.length; i++) {
                const commentUser = commentUsers[i];

                console.log(commentUser.id)
                if (String(id) === String(commentUser.id)) {
                    const shareIcon = currentPageShareIcons[i]; // 当前页内的相对索引
                    console.log(shareIcon)
                    shareIcon.style.display = 'block';
                    console.log(1111)
                }
            }

            // 绑定删除事件
            Array.from(currentPageShareIcons).forEach(shareIcon => {
                shareIcon.addEventListener('click', () => {
                    const commentId = Number(shareIcon.dataset.value);
                    console.log(commentId)
                    $.ajax({
                        url: `/videos/comment/user`,
                        type: 'POST',
                        data: { commentId:commentId },
                        success: (result) => {
                            showCustomAlert('删除成功', 3000);
                            totalCommentsCount = 0;
                            // 删除后重新加载当前页（可选：优化为局部删除）
                            if (comments.length === 0 && currentPage > 1) {
                                currentPage--;
                                // 重新加载上一页
                            }
                            loadComments(postIdNum, currentPage);
                        },
                        error: (error) => {
                            showCustomAlert('删除失败: ' + error.statusText, 3000);
                        }
                    });
                });
            });

            // 绑定点赞事件
            Array.from(replyIcons).forEach((replyIcon, i) => {
                replyIcon.addEventListener('click', () => {
                    const commentId = Number(replyIcon.dataset.value);
                    if (replyIcon.style.color === 'red') {
                        // 取消点赞
                        $.ajax({
                            url: `/videos/cancelLike`,
                            type: 'POST',
                            data: { commentsId: commentId },
                            success: () => {
                                showCustomAlert('取消点赞成功', 3000);
                                commentLikeIcons[i].style.color = 'rgb(82, 91, 100)';
                                replyIcon.style.color = 'rgb(82, 91, 100)';
                            }
                        });
                    } else {
                        // 点赞
                        $.ajax({
                            url: `/videos/like`,
                            type: 'POST',
                            data: {commentsId: commentId  },
                            success: () => {
                                showCustomAlert('点赞成功', 3000);
                                commentLikeIcons[i].style.color = 'red';
                                replyIcon.style.color = 'red';
                            }
                        });
                    }
                });
            });

            // 初始化点赞状态
            comments.forEach((comment, i) => {
                if (comment.isLiked) {
                    commentLikeIcons[i].style.color = 'red';
                    replyIcons[i].style.color = 'red';
                }
            });

            isLoading = false; // 加载完成
        },
        error: (error) => {
            currentPage--; // 加载失败时回退页码
            isLoading = false;
            showCustomAlert('加载评论失败: ' + error.statusText, 3000);
        }
    });


}
// let follow_button = document.querySelector('.follow-button');
follow_button.addEventListener('click', function() {
    let userId = this.value;
    console.log(userId);
    // const userIdNum = Number(value);
    if (this.classList.contains('following')) {
        // 当前是已关注状态，执行取消关注逻辑
        $.ajax({
            url: `/cancelFollow?id=${userId}`,
            type: 'POST',
            success: function(result) {
                showCustomAlert('取消关注成功', 3000);
                follow_button.classList.remove('following');
                follow_button.textContent = '关注';
            },
            error: function(error) {
                showCustomAlert('取消关注失败: ' + error.statusText, 3000);
            }
        });
    }
    else {
        // 当前是未关注状态，执行关注逻辑
        $.ajax({
            url: `/followOthers?id=${userId}`,
            type: 'GET',
            success: function(result) {
                showCustomAlert('关注成功', 3000);
                follow_button.classList.add('following');
                follow_button.textContent = '取消关注';
            },
            error: function(error) {
                showCustomAlert('关注失败: ' + error.statusText, 3000);
            }
        });
    }
})
